package theeg.DependencyAnalysis.Core.Algorithms.SubstringDetection;

import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static LEX.LanguageExtensions.*;

public class Node {

    public SuffixTree tree;
    public Node suffixNode;
    private final HashMap<Character, Edge> _edges;
    private Edge[] _edgesTemp;
    private final int _nodeNumber;

    public Character atIndex(int index) {
        return tree.getText()[index];
    }

    public Node(SuffixTree tree, Node suffixNode) {
        this.tree = tree;
        this.suffixNode = suffixNode;
        _edges = new HashMap();
        _nodeNumber = this.tree.createNewNodeNumber();
    }

    public void addEdge(int index, Edge edge) {
        _edges.put(tree.getText()[index], edge);
        _edgesTemp = null;
    }

    public void removeEdge(int index) {
        _edges.remove(tree.getText()[index]);
        _edgesTemp = null;
    }

    public Edge findEdge(char ch) {
        if (_edges.containsKey(ch)) {
            return _edges.get(ch);
        }
        return null;
    }

    private final Lock _edgesLock = new ReentrantLock();

    public Edge[] getEdges() {
        lock(_edgesLock, () -> {
            if (_edgesTemp == null) {
                _edgesTemp = (Edge[]) _edges.values().toArray();
            }
        });
        return _edgesTemp;
    }

    @Override
    public int hashCode() {
        return _nodeNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }

        Node node = (Node) obj;
        return _nodeNumber == node._nodeNumber;
    }
}
